<template>
  <div>
    <el-dialog title="新增" width="40%" :visible.sync="dialogVisible" :destroy-on-close="true" @close="handleCloseDialog">
      <el-form ref="formData" :model="formData" label-width="80px" :rules="formRules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="formData.remarks" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click.native="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click.native="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        id: '',
        name: '',
        code: '',
        remarks: ''
      },
      formRules: {
        code: [
          { required: true, message: '请输入角色编码' }
        ]
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.showDialog
      },
      set(val) {
        this.$emit('update:showDialog', val)
      }
    }
  },
  methods: {
    getFormData(id) {
      this.$api.role.find(id).then(res => {
        this.formData = res.data
      })
    },
    submitForm() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          if (!this.formData.id) {
            this.$api.role.save(this.formData).then(res => {
              if (res.code === 20000) {
                this.dialogVisible = false
                this.$emit('submitSuccess')
              }
            }).catch(err => {
              console.log(err)
            })
          } else {
            this.$api.role.update(this.formData).then(res => {
              if (res.code === 20000) {
                this.dialogVisible = false
                this.$emit('submitSuccess')
              }
            })
          }
        }
      })
    },
    handleCloseDialog() {
      Object.assign(this.formData, this.$options.data().formData)
    }
  }
}

</script>
<style scoped>
</style>
